<?php
namespace ua_backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use ua_backend\models\AdminLoginForm;
use ua_backend\models\Admin;
use yii\rbac\DbManager;
use yii\helpers\ArrayHelper;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public $role;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'register', 'error', 'off'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
//        print_r(Yii::$app->session);
//        echo '<br>';
//        print_r(Yii::$app->request);exit;

        if (!Yii::$app->user->isGuest){
            $this->role = Yii::$app->user->identity->role;
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
         $userId = Yii::$app->user->getId();
//         $role = Yii::$app->authManager->getRolesByUser($userId);

//        return $this->render('index', ['id'=> $userId]);
        return $this->redirect('/shops/index');
    }

    public function actionOff(){
        return $this->render('off');
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {

//            $role = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
//            print_r($role);return;exit;

//            if(isset($role['后台普通'])){
//                return $this->redirect('/shops/index');
//            }else{
//                return $this->redirect('/shops/index');
//            }
            return $this->redirect('/shops/index');
        }

        $model = new AdminLoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
//            return $this->goBack();
            return $this->redirect('/shops/index');
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionRegister()
    {
        $model = new Admin();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->generateAuthKey();
            $model->auth_key = $model->getAuthKey();
            $model->setPassword($_POST['Admin']['password']);
            $model->created_at = $model->updated_at = time();
            $model->role = 30;
            $model->code = $this->setCode();

            if($model->save()){
//                $role = ($_POST['Admin']['role'] == 30)?'后台管理':'后台普通';
                $role = '后台普通';
                $auth = new DbManager;
                $auth->init();
                $obj = $auth->getRole($role);
                $auth->assign($obj, $model->id);

                Yii::$app->user->login($model, 3600 * 24 * 30);
                return $this->redirect(['./']);
//                return
            }
        }

        return $this->render('reg', [
            'model' => $model,
        ]);
    }

    protected function setCode(){
        $chars = Yii::$app->params['Chars'];
        $codes = '';
        for($i=0; $i<4; $i++){
            $codes .= $chars[mt_rand(0,35)];
        }

        $count = Admin::find()->where(['code'=>$codes])->count();
        if($count>0){ return $this->setCode(); }

        return $codes;
    }

    // Curl Get 方法
    protected function curl_get($url){
        $header = array('Accept: application/json');
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($curl);
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);
        } else {
            return $data;
            curl_close($curl);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}
